import React, { useState, useEffect } from 'react';
import { Navigate } from 'react-router-dom';
import { Spin, Button, message, Alert } from 'antd';
import { ReloadOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { useAuth } from '../store/AuthContext';
import { runAuthDiagnostics, getFriendlyErrorMessage, AuthDiagnostics } from '../utils/authDiagnostics';

interface ProtectedRouteProps {
  children: React.ReactNode;
}

const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ children }) => {
  const { user, loading, isInitializing } = useAuth();
  const [retryCount, setRetryCount] = useState(0);
  const [showRetry, setShowRetry] = useState(false);
  const [diagnostics, setDiagnostics] = useState<AuthDiagnostics | null>(null);

  useEffect(() => {
    // 如果加载超过10秒，运行诊断
    const timer = setTimeout(async () => {
      if (loading && !user) {
        const diag = await runAuthDiagnostics();
        setDiagnostics(diag);
        setShowRetry(true);
      }
    }, 10000);

    return () => clearTimeout(timer);
  }, [loading, user]);

  const handleRetry = () => {
    setRetryCount(prev => prev + 1);
    setShowRetry(false);
    // 刷新页面重新验证
    window.location.reload();
  };

  if (loading) {
    return (
      <div style={{ 
        display: 'flex', 
        flexDirection: 'column',
        justifyContent: 'center', 
        alignItems: 'center', 
        height: '100vh',
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        color: 'white'
      }}>
        <Spin size="large" style={{ color: 'white' }} />
        <div style={{ marginTop: '20px', fontSize: '16px' }}>
          {isInitializing ? '正在验证身份...' : '正在加载...'}
        </div>
        {showRetry && (
          <div style={{ marginTop: '20px', maxWidth: '400px', textAlign: 'center' }}>
            {diagnostics && (
              <Alert
                message={getFriendlyErrorMessage(diagnostics)}
                type="warning"
                icon={<ExclamationCircleOutlined />}
                style={{ 
                  marginBottom: '16px',
                  background: 'rgba(255,255,255,0.1)',
                  border: '1px solid rgba(255,255,255,0.2)',
                  color: 'white'
                }}
                description={
                  diagnostics.recommendations.length > 0 && (
                    <div style={{ marginTop: '8px', fontSize: '12px' }}>
                      <div>建议：</div>
                      <ul style={{ margin: '4px 0', paddingLeft: '16px' }}>
                        {diagnostics.recommendations.map((rec, index) => (
                          <li key={index}>{rec}</li>
                        ))}
                      </ul>
                    </div>
                  )
                }
              />
            )}
            <Button 
              type="primary" 
              icon={<ReloadOutlined />}
              onClick={handleRetry}
              style={{ 
                background: 'rgba(255,255,255,0.2)', 
                border: '1px solid rgba(255,255,255,0.3)',
                color: 'white'
              }}
            >
              重试连接
            </Button>
            <div style={{ marginTop: '10px', fontSize: '12px', opacity: 0.8 }}>
              如果问题持续存在，请检查网络连接或联系技术支持
            </div>
          </div>
        )}
      </div>
    );
  }

  if (!user) {
    return <Navigate to="/login" replace />;
  }

  return <>{children}</>;
};

export default ProtectedRoute;
